package com.candy.security.jwt.handle;

import com.candy.common.result.R;
import com.candy.security.jwt.entity.CandyUserdetails;
import com.candy.security.jwt.entity.LoginUser;
import com.candy.security.jwt.service.TokenService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
	@Autowired
	TokenService tokenService;

	@Resource
	private ObjectMapper objectMapper;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException
	{
		resp.setContentType("application/json;charset=UTF-8");
		// 用户验证
		CandyUserdetails candyUserdetails = (CandyUserdetails) authentication.getPrincipal();
		LoginUser loginUser = candyUserdetails.getLoginUser();
		// 生成token
		String token = tokenService.createToken(loginUser);
		R jsonData = new R(HttpStatus.OK, "");
		jsonData.put("token",token);
		jsonData.put("loginName",loginUser.getLoginName());
		PrintWriter out = resp.getWriter();
		out.write(objectMapper.writeValueAsString(jsonData));
		out.flush();
		out.close();
	}
}